package com.easyoffer.job.once;

import com.easyoffer.esdao.QuestionEsDao;
import com.easyoffer.model.dto.question.QuestionEsDTO;
import com.easyoffer.model.entity.Question;
import com.easyoffer.service.QuestionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

//@Component
@Slf4j
public class FullQuestionToEsJob implements CommandLineRunner {

    @Resource
    private QuestionEsDao questionEsDao;
    @Resource
    private QuestionService questionService;
    @Override
    public void run(String... args) throws Exception {
        //数据量不大情况下用list直接获取
        List<Question> list = questionService.list();
        List<QuestionEsDTO> questionEsDTOList = list.stream().map(question -> {
            return QuestionEsDTO.objToDto(question);
        }).collect(Collectors.toList());

        //将数据存到es中
        int pageSize = 500;
        int total = questionEsDTOList.size();
        log.info("FullCopyToEs start , total {}",total);
        for (int i = 0; i < total; i += pageSize) {
            int end = Math.min(i + pageSize, questionEsDTOList.size());
            log.info("Copy from {} to {}",i,end);
            List<QuestionEsDTO> subList = questionEsDTOList.subList(i, end);
            questionEsDao.saveAll(subList);
        }
        log.info("FullCopyToEs end , total {}",total);

    }
}
